package com.example.controller;

import com.example.entity.FinancialIndicator;
import com.example.entity.CreditBehavior;
import com.example.repository.FinancialIndicatorRepository;
import com.example.repository.CreditBehaviorRepository;
import com.example.service.FinancialIndicatorService;
import com.example.service.CreditBehaviorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 风控数据REST控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/risk")
public class RiskControlController {

    @Autowired
    private FinancialIndicatorRepository financialIndicatorRepository;

    @Autowired
    private CreditBehaviorRepository creditBehaviorRepository;

    @Autowired
    private FinancialIndicatorService financialIndicatorService;

    @Autowired
    private CreditBehaviorService creditBehaviorService;

    /**
     * 获取用户财务指标
     */
    @GetMapping("/financial/{userId}")
    public ResponseEntity<?> getFinancialIndicator(@PathVariable Long userId) {
        try {
            Optional<FinancialIndicator> indicator = financialIndicatorRepository.findByUserId(userId);
            if (indicator.isPresent()) {
                return ResponseEntity.ok(indicator.get());
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("获取用户财务指标失败: userId={}", userId, e);
            return ResponseEntity.internalServerError().body("获取数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户信贷行为
     */
    @GetMapping("/credit/{userId}")
    public ResponseEntity<?> getCreditBehavior(@PathVariable Long userId) {
        try {
            Optional<CreditBehavior> creditBehavior = creditBehaviorRepository.findByUserId(userId);
            if (creditBehavior.isPresent()) {
                return ResponseEntity.ok(creditBehavior.get());
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("获取用户信贷行为失败: userId={}", userId, e);
            return ResponseEntity.internalServerError().body("获取数据失败: " + e.getMessage());
        }
    }

    /**
     * 计算用户财务指标
     */
    @PostMapping("/financial/calculate/{userId}")
    public ResponseEntity<?> calculateFinancialIndicators(@PathVariable Long userId) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            double dti = financialIndicatorService.calculateDTI(userId);
            double disposableIncome = financialIndicatorService.calculateDisposableIncome(userId);
            double incomeVolatility = financialIndicatorService.calculateIncomeVolatility(userId);
            
            result.put("userId", userId);
            result.put("debtToIncomeRatio", dti);
            result.put("disposableIncome", disposableIncome);
            result.put("incomeVolatility", incomeVolatility);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("计算用户财务指标失败: userId={}", userId, e);
            return ResponseEntity.internalServerError().body("计算失败: " + e.getMessage());
        }
    }

    /**
     * 计算用户信贷指标
     */
    @PostMapping("/credit/calculate/{userId}")
    public ResponseEntity<?> calculateCreditIndicators(@PathVariable Long userId) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            double utilizationRate = creditBehaviorService.calculateCreditCardUtilizationRate(userId);
            int comprehensiveScore = creditBehaviorService.getComprehensiveCreditScore(userId);
            int overdueRisk = creditBehaviorService.analyzeOverdueRisk(userId);
            
            result.put("userId", userId);
            result.put("creditCardUtilizationRate", utilizationRate);
            result.put("comprehensiveCreditScore", comprehensiveScore);
            result.put("overdueRisk", overdueRisk);
            result.put("riskLevel", getRiskLevelText(overdueRisk));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("计算用户信贷指标失败: userId={}", userId, e);
            return ResponseEntity.internalServerError().body("计算失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户综合风控评估
     */
    @GetMapping("/assessment/{userId}")
    public ResponseEntity<?> getUserRiskAssessment(@PathVariable Long userId) {
        try {
            Map<String, Object> assessment = new HashMap<>();
            
            // 获取基础数据
            Optional<FinancialIndicator> financialOpt = financialIndicatorRepository.findByUserId(userId);
            Optional<CreditBehavior> creditOpt = creditBehaviorRepository.findByUserId(userId);
            
            if (financialOpt.isEmpty() && creditOpt.isEmpty()) {
                return ResponseEntity.notFound().build();
            }
            
            assessment.put("userId", userId);
            
            // 财务指标评估
            if (financialOpt.isPresent()) {
                FinancialIndicator financial = financialOpt.get();
                assessment.put("monthlyIncome", financial.getMonthlyIncome());
                assessment.put("debtToIncomeRatio", financial.getDebtToIncomeRatio());
                assessment.put("disposableIncome", financial.getDisposableIncome());
            }
            
            // 信贷行为评估
            if (creditOpt.isPresent()) {
                CreditBehavior credit = creditOpt.get();
                assessment.put("creditCardUtilizationRate", credit.getCreditCardUtilizationRate());
                assessment.put("historicalOverdueCount", credit.getHistoricalOverdueCount());
                
                int overdueRisk = creditBehaviorService.analyzeOverdueRisk(userId);
                assessment.put("overdueRisk", overdueRisk);
                assessment.put("riskLevel", getRiskLevelText(overdueRisk));
            }
            
            return ResponseEntity.ok(assessment);
        } catch (Exception e) {
            log.error("获取用户风控评估失败: userId={}", userId, e);
            return ResponseEntity.internalServerError().body("评估失败: " + e.getMessage());
        }
    }

    /**
     * 保存财务指标数据
     */
    @PostMapping("/financial")
    public ResponseEntity<?> saveFinancialIndicator(@RequestBody FinancialIndicator indicator) {
        try {
            FinancialIndicator saved = financialIndicatorRepository.save(indicator);
            return ResponseEntity.ok(saved);
        } catch (Exception e) {
            log.error("保存财务指标失败", e);
            return ResponseEntity.internalServerError().body("保存失败: " + e.getMessage());
        }
    }

    /**
     * 保存信贷行为数据
     */
    @PostMapping("/credit")
    public ResponseEntity<?> saveCreditBehavior(@RequestBody CreditBehavior creditBehavior) {
        try {
            CreditBehavior saved = creditBehaviorRepository.save(creditBehavior);
            return ResponseEntity.ok(saved);
        } catch (Exception e) {
            log.error("保存信贷行为失败", e);
            return ResponseEntity.internalServerError().body("保存失败: " + e.getMessage());
        }
    }

    /**
     * 获取风险等级文本描述
     */
    private String getRiskLevelText(int riskLevel) {
        switch (riskLevel) {
            case 0: return "低风险";
            case 1: return "中风险";
            case 2: return "高风险";
            default: return "未知";
        }
    }
}